<template>
  <div>
    <form style="width: 500px; margin: 50px auto" @submit.prevent="register">
      <div class="form-group">
        <label for="username">用户名：</label>
        <input
          @change="checkUsername"
          class="form-control"
          :class="{ 'is-invalid': usernameCheck }"
          type="text"
          v-model="username"
          placeholder="请输入用户名"
        />
        <div class="invalid-feedback">用户名已存在</div>
      </div>
      <div class="form-group">
        <label for="password">密码：</label>
        <input
          class="form-control"
          :class="{ 'is-invalid': rePasswordCheck }"
          type="password"
          v-model="password"
          placeholder="请输入密码"
        />
      </div>
      <div class="form-group">
        <label for="repassword">确认密码：</label>
        <input
          @change="checkRePassword"
          class="form-control"
          :class="{ 'is-invalid': rePasswordCheck }"
          type="password"
          v-model="repassword"
          placeholder="请输入确认密码"
        />
        <div class="invalid-feedback">两次密码输入不一致</div>
      </div>
      <div class="form-group">
        <label for="mobile">手机号：</label>
        <input
          class="form-control"
          type="text"
          v-model="mobile"
          placeholder="请输入手机号"
        />
      </div>
      <input
        type="submit"
        class="btn btn-primary btn-lg"
        style="width: 500px"
        value="注册"
      />
    </form>
  </div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      username: "",
      usernameCheck: false,
      password: "",
      repassword: "",
      rePasswordCheck: false,
      mobile: "",
    };
  },
  methods: {
    register() {
      this.axios
        .post("/api/user/register", {
          username: this.username,
          password: this.password,
          mobile: this.mobile,
        })
        .then((res) => {
          console.log(res);
          // 存储
          if (res.data.code == 200) {
            this.saveUser(res.data.data);
            this.$router.push("/");
          }
        });
    },
    checkUsername() {
      let username = this.username;
      this.axios
        .get("/api/user/checkUsername?username=" + username)
        .then((res) => {
          console.log(res);
          if (res.data.code != 200) {
            this.usernameCheck = true;
          } else {
            this.usernameCheck = false;
          }
        });
    },
    checkRePassword() {
      if (this.password != this.repassword) {
        this.rePasswordCheck = true;
      } else {
        this.rePasswordCheck = false;
      }
    },
    ...mapMutations(["saveUser"]),
  },
};
</script>
